import math
from datetime import datetime

from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.house import models
from django.http import *
from django.core.cache import cache

from apps.order.models import Order
from ihome_01 import settings
from utils.views import LoginRequiredJSONMixin
from utils.fileupdate import updatefile
import logging
import re
import json


class AreaView(View):
    '''城区列表'''

    def get(self, request):
        # 获取缓存
        if cache.get('area_list'):
            # 如果有缓存数据则直接return,否则继续向下执行
            return JsonResponse({'errno': 0, 'errmsg': '成功获取缓存', 'data': cache.get('area_list')})
        # 获取tb_area中所有数据
        try:
            # 无数据返回空QuerySet
            area_data = models.Area.objects.all()
            # models.Area.objects.all()
        # except models.Area.DoesNotExist:
        except:
            return JsonResponse({'errno': 4004, 'errmsg': '数据库错误'})
        # 初始化存储列表
        area_list = []
        for area in area_data:
            area_list.append({
                'aid': area.id,
                'aname': area.name,
            })
        # 设置缓存3600秒
        cache.set('area_list', area_list, 60 * 60)
        return JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': area_list})


class SetHouseView(View, LoginRequiredJSONMixin):
    # 设置房屋数据
    def post(self, request):
        # 获取房屋参数
        horsedata = json.loads(request.body.decode())
        title = horsedata.get('title')
        price = horsedata.get('price')
        area_id = horsedata.get('area_id')
        address = horsedata.get('address')
        room_count = horsedata.get('room_count')
        acreage = horsedata.get('acreage')
        unit = horsedata.get('unit')
        capacity = horsedata.get('capacity')
        beds = horsedata.get('beds')
        deposit = horsedata.get('deposit')
        min_days = horsedata.get('min_days')
        max_days = horsedata.get('max_days')
        facility = horsedata.get('facility')  # arraylist
        # 判断参数是否完整
        if not all((title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days,
                    max_days, facility)):
            return JsonResponse({'errno': 4103, 'errmsg': '参数不全'})
        # 判断房屋价格
        if int(price) <= 0:
            return JsonResponse({'errno': 4103, 'errmsg': '价格不合理'})

        # 判断地区id是否正确
        # if re.match("",area_id)
        try:
            models.Area.objects.get(id=area_id)
        except Exception as e:
            return JsonResponse({'errno': 4103, 'errmsg': '地区错误'})
        # 判断房间数目是否正确
        if int(room_count) <= 0:
            return JsonResponse({'errno': 4103, 'errmsg': '房间数错误'})
        # 判断房间面积是否正确
        if int(acreage) <= 0:
            return JsonResponse({'errno': 4103, 'errmsg': '面积错误'})

        # 验证通过后写入数据库
        '''
               title = horsedata.get('title')
        price = horsedata.get('price')
        area_id = horsedata.get('area_id')
        address = horsedata.get('address')
        room_count = horsedata.get('room_count')
        acreage = horsedata.get('acreage')
        unit = horsedata.get('unit')
        capacity = horsedata.get('capacity')
        beds = horsedata.get('beds')
        deposit = horsedata.get('deposit')
        min_days = horsedata.get('min_days')
        max_days = horsedata.get('max_days')
        facility = horsedata.get('facility')
        '''
        try:
            horse_info = models.House.objects.create(
                # user=房屋主人的用户编号
                user_id=request.user.id,
                title=title,
                area_id=area_id,
                address=address,
                price=price,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days,
                # order_count
                # facility=facility,
            )
        except Exception as e:
            return JsonResponse({'errno': 4103, 'errmsg': str(e)})
        # id__in:iterable->arraylist
        # 通过前端提交的数组id，获取数据库中的设施id
        facility_queryset = models.Facility.objects.filter(id__in=facility)
        # #遍历已获取的设施集合并写入数据库
        # for facility_parmary in facility_queryset:
        #     horse_info.facility.add(facility_parmary)

        # 写入设施数据
        horse_info.facility.add(*facility_queryset)
        horse_info.save()
        return JsonResponse({
            "errno": "0",
            "errmsg": "发布成功",
            "data": {
                "house_id": horse_info.id,
            }
        })

    # 搜索房屋数据：
    def get(self, request):
        # 接受参数
        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p')
        #如果无参查询，则返回所有数据

        #通过日期函数格式化
        #update sql: "%Y-%m-%d"
        '''
        %y 两位数的年份表示（00-99）
        %Y 四位数的年份表示（000-9999）
        %m 月份（01-12）
        %d 月内中的一天（0-31）
        %H 24小时制小时数（0-23）
        %I 12小时制小时数（01-12）
        %M 分钟数（00-59）
        %S 秒（00-59）
        '''
        # 根据区域id进行查询判断是否存在
        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p')
        if sk == 'booking':
            try:
                house_obj = models.House.objects.filter(area_id=aid).order_by('-order_count')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': '查询数据库出错'})
        elif sk == 'price-inc':
            try:
                house_obj = models.House.objects.filter(area_id=aid).order_by('price')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': '查询数据库出错'})
        elif sk == 'price-des':
            try:
                house_obj = models.House.objects.filter(area_id=aid).order_by('-price')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': '查询数据库出错'})
        else:
            try:
                house_obj = models.House.objects.filter(area_id=aid).order_by('-id')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': '查询数据库出错'})
        for house in house_obj:
            try:
                count = Order.objects.filter(house=house, begin_date__lte=ed, end_date__gte=sd).count()
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': '查询数据库出错'})
            if count > 0:
                return JsonResponse({'errno': 4001, 'errmsg': '该日期未搜到可定房源'})

        houses = []
        for house in house_obj:
            houses.append({
                "address": house.address,
                "area_name": house.area.name,
                "ctime": datetime.strftime(house.create_time, '%Y-%m-%d'),
                "house_id": house.id,
                "img_url": house.index_image_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": str(house.user.avatar)
            })

        data = {
            'houses': houses,
            "total_page": p
        }
        return JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})



class SetHouseImg(View, LoginRequiredJSONMixin):
    def post(self, request, house_id):

        house_img = request.FILES.get('house_image')
        house_img_data = house_img.read()
        # 判断参数
        if not house_img:
            return JsonResponse({"errno": 4103})
        if not house_img.name.lower().endswith(('.bmp', '.jpg', '.jpeg', '.png')):
            return JsonResponse({'errno': 4103, 'errmsg': '图片格式错误'})
        returnUrl = updatefile(
            settings.QI_NIU_ACCESS_KEY,
            settings.QI_NIU_SECRET_KEY,
            settings.BURCKET_NAME,
            settings.QI_NIU_DORMAIN_NAME,
            house_img_data
        )
        house = models.House.objects.get(id=house_id)
        # 判断：如果没有url则添加url
        if not house.index_image_url:
            house.index_image_url = returnUrl
            house.save()
        # 通过HouseImage模型类保存数据
        house_image = models.HouseImage()
        house_image.house = house
        house_image.url = returnUrl
        house_image.save()
        return JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': {'url': returnUrl}})


class MyHouseView(View, LoginRequiredJSONMixin):

    def get(self, request):
        """房屋列表业务逻辑实现"""
        # 获取登录用户
        user = request.user
        try:
            houses = models.House.objects.filter(user_id=user.id)
        except:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库错误'})

        # 构造房屋列表
        houses_list = []
        for house in houses:
            # try:
            #     user_avatar = house.user.avatar.url
            # except:
            #     user_avatar = None
            houses_list.append({
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time.strftime("%Y-%m-%d"),
                "house_id": house.id,
                "img_url": str(house.index_image_url),
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": str(house.user.avatar)
            })
        # 返回响应
        return JsonResponse({
            'data': {'houses': houses_list},
            'errno': 0,
            'errmsg': 'ok'
        })

class HouseDetal(View):
    #无需登陆
    def get(self,request,house_id):
        #登陆用户
        if request.user:
            user_id = request.user.id
            if not house_id:
                return JsonResponse({'errno': 4103, 'errmsg': '缺失必传参数'})
            try:
                house = models.House.objects.get(pk=house_id)
                facilites = house.facility.all()
                houseimages = house.houseimage_set.filter(house=house)
                orders = house.order_set.all()
            except Exception as e:
                return JsonResponse({'errno': 4004, 'errmsg': '查询数据库出错'})
            comments = []
            for order in orders:
                comments.append({
                    "comment": order.comment,
                    "ctime": datetime.strftime(order.update_time, '%Y-%m-%d'),
                    "user_name": order.user.username
                })
            list = []
            for facilitty in facilites:
                list.append(facilitty.id)
            # 获取房屋图片
            images = []
            for houseimage in houseimages:
                images.append(houseimage.url)

            data_house = {
                "acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comments,
                "deposit": house.deposit,
                "facilities": list,
                "hid": house_id,
                "img_urls": images,
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": str(house.user.avatar),
                "user_id": house.user.id,
                "user_name": house.user.username
            }

            data = {
                'house': data_house,
                "user_id": user_id
            }
            return JsonResponse({'errno': 0, 'errmsg': 'OK', 'data': data})

        #匿名用户
        else:
            user_id = -1
            user_name = 'anonymous_user'
            if not house_id:
                return JsonResponse({'errno': 4103, 'errmsg': '缺失必传参数'})
            try:
                house = models.House.objects.get(pk=house_id)
                facilites = house.facility.all()
                houseimages = house.houseimage_set.filter(house=house)
                orders = house.order_set.all()
            except Exception as e:
                return JsonResponse({'errno': 4004, 'errmsg': '查询数据库出错'})
            comments = []
            for order in orders:
                comments.append({
                    "comment": order.comment,
                    "ctime": datetime.strftime(order.update_time, '%Y-%m-%d'),
                    "user_name": order.user.username
                })
            list = []
            for facilitty in facilites:
                list.append(facilitty.id)
            # 获取房屋图片
            images = []
            for houseimage in houseimages:
                images.append(houseimage.url)

            data_house = {
                "acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comments,
                "deposit": house.deposit,
                "facilities": list,
                "hid": house_id,
                "img_urls": images,
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": str(house.user.avatar),
                "user_id": house.user.id,
                "user_name": house.user.username
            }

            data = {
                'house': data_house,
                "user_id": user_id
            }
            return JsonResponse({'errno': 0, 'errmsg':'ok','data':data})

class HouseIndex(View):
    def get(self,request):
        try:
            houses = models.House.objects.order_by("-create_time")[0:5]
        except:
            return JsonResponse({'errno': 4004, 'errmsg': '数据库错误'})
        house_recommend_list = []
        for house in houses:
            house_recommend_list.append({
                "house_id": house.id,
                "img_url": house.index_image_url,
                "title": house.title
            })

        return JsonResponse({
            'data': house_recommend_list,
            'errno': 0,
            'errmsg': 'ok'
        })
